package com.esun.dao.das;

import com.alibaba.excel.util.StringUtils;
import com.esun.dao.eo.BaseEo;
import com.esun.dao.eo.PageEo;
import com.esun.dao.eo.SortEo;
import com.esun.dao.mapper.BaseMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.CaseFormat;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import java.util.List;

/**
 * 基础数据业务
 *
 * @author John.xiao
 * @date 2021/7/25 22:27
 */
@Repository
@Data
@Slf4j
public abstract class BaseDas<T extends BaseEo> {

	BaseMapper<T> baseMapper;

	public BaseMapper<T> getBaseMapper() {
		return baseMapper;
	}

	public void setBaseMapper(BaseMapper<T> baseMapper) {
		this.baseMapper = baseMapper;
	}

	public void init(){ }

	T queryById(Integer id){
		init();
		return baseMapper.queryById(id);
	}

	PageInfo<T> queryAll(T entity, PageEo pageEo){
		init();
		PageHelper.startPage(pageEo.getPageIndex(),pageEo.getPageSize());
		List<T> entityList = baseMapper.queryAll(entity);
		return new PageInfo<>(entityList);
	}

	public PageInfo<T> queryPageBySort(T entity, PageEo pageEo, List<SortEo> sortList){
		init();
		StringBuilder orderByClause = new StringBuilder();
		for(SortEo sortEo : sortList){
			orderByClause.append(getColumnName(sortEo.getSortParam()));
			if (!sortEo.getAscending()){
				orderByClause.append(" ").append("desc");
			}
			orderByClause.append(",");
		}
		if (!StringUtils.isEmpty(orderByClause.toString())){
			orderByClause.deleteCharAt(orderByClause.length()-1);
		}
		entity.setOrderByClause(orderByClause.toString());
		PageHelper.startPage(pageEo.getPageIndex(),pageEo.getPageSize());
		List<T> entityList = baseMapper.queryBatchBySort(entity);
		return new PageInfo<>(entityList);
	}

	public List<T> queryAll(T entity) {
		init();
		return baseMapper.queryAll(entity);
	}

	public int insert(T entity) {
		init();
		return baseMapper.insert(entity);
	}

	public int insertBatch(List<T> entityList) {
		init();
		return baseMapper.insertBatch(entityList);
	}

	public int update(T entity) {
		init();
		return baseMapper.update(entity);
	}

	@Deprecated
	public int insertOrUpdateBatch(List<T> entityList) {
		init();
		return baseMapper.insertOrUpdateBatch(entityList);
	}

	public int deleteById(int id) {
		init();
		return baseMapper.deleteById(id);
	}

	public int delete(T entity) {
		init();
		return baseMapper.delete(entity);
	}

	public int deleteByIdBatch(List<T> entityList) {
		init();
		return baseMapper.deleteByIdBatch(entityList);
	}

	/**
	 * 排序参数与数据表字段映射
	 *
	 * @param property 排序参数
	 * @return 数据库字段
	 */
	public String getColumnName(String property) {
		return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, property);
	}

}
